package cn.edu.hubu.hubusmartmedicalsystem.service.impl;

import cn.edu.hubu.hubusmartmedicalsystem.entity.Admin;
import cn.edu.hubu.hubusmartmedicalsystem.mapper.AdminMapper;
import cn.edu.hubu.hubusmartmedicalsystem.service.AdminService;
import cn.edu.hubu.hubusmartmedicalsystem.vo.ResultVO;
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;


@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    // 登录
    @Override
    public ResultVO<Admin> login(String adminId, String adminPwd) {
        Admin admin = adminMapper.selectByID(adminId);
        if (admin == null) {
            return new ResultVO<>(500, "管理员不存在", null);
        }
        // 校验密码（MD5加密验证）
        String hashedPassword = DigestUtil.md5Hex(adminPwd);
        if (!hashedPassword.equals(admin.getAdminPwd())) {
            return new ResultVO<>(500, "密码错误", null);
        }
        return new ResultVO<>(200, "登录成功", admin);
    }

    // 查询管理员
    @Override
    public ResultVO<Admin> getAdminById(String adminId) {
        Admin admin = adminMapper.selectByID(adminId);
        if (admin == null) {
            return new ResultVO<>(500, "管理员不存在", null);
        }
        return new ResultVO<>(200, "查询成功", admin);
    }

    @Override
    public ResultVO<List<Admin>> getAllAdmin() {
        List<Admin> admins = adminMapper.selectAll();
        if (admins == null || admins.isEmpty()) {
            return new ResultVO<>(500, "没有找到任何设备", null);
        }
        return new ResultVO<>(200, "查询成功", admins);
    }



    // 注册管理员
    @Override
    public ResultVO<String> registerAdmin(Admin admin) {
        if (adminMapper.selectByID(admin.getAdminId()) != null){
            return new ResultVO<>(500,"该管理员已存在",null);
        }
        String hashedPassword = DigestUtil.md5Hex(admin.getAdminPwd());
        admin.setAdminPwd(hashedPassword);
        int result = adminMapper.insertAdmin(admin);
        if (result > 0) {
            return new ResultVO<>(200, "注册成功", null);
        }else {
            return new ResultVO<>(500, "注册失败", null);
        }
    }

    // 删除管理员
    @Override
    public ResultVO<String> deleteAdmin(String adminId) {
        int result = adminMapper.deleteByID(adminId);
        if (result > 0) {
            return new ResultVO<>(200, "删除成功", null);
        }
        return new ResultVO<>(500, "删除失败", null);
    }
}
